package along.com.myboxugu.fragment;


import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;


import along.com.myboxugu.R;
import along.com.myboxugu.activity.CourseDetailActivity;
import along.com.myboxugu.activity.CourseModel;

/**
 * A simple {@link Fragment} subclass.
 */
public class CourseFragment extends Fragment {
    ViewPager mViewpager;
    RecyclerView mRecycleView;
    int curentpostion ;
    public ArrayList<CourseModel.Course> courselists =new ArrayList<>();
    public ArrayList<ImageView> mViewPagerImgs = new ArrayList<>();
   Handler handler = new Handler(new Handler.Callback(){

       @Override
       public boolean handleMessage(Message message) {
           handler.sendEmptyMessageDelayed(1,2000);
           curentpostion ++;
           mViewpager.setCurrentItem(curentpostion % mViewPagerImgs.size());
           return false;
       }
   });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_course, container, false);
        mRecycleView=view.findViewById(R.id.recyclerView);
        mViewpager =view.findViewById(R.id.viewpager);
        login();
        return view;
    }
    public void login(){
        RequestParams params = new RequestParams("http://1633.applinzi.com/public/?s=App.Course.Getcourse");
        x.http().get(params, new Callback.CommonCallback<String>() {  //

            @Override
            public void onSuccess(String result) {
                Gson gson =new Gson();  //Gson解析json（LoginModel）文件
                CourseModel courseModel = gson.fromJson(result, CourseModel.class);
                if (courseModel!=null&&courseModel.data!=null&&courseModel.data.courselist!=null){
                    courselists  =courseModel.data.courselist;
                }
                GridLayoutManager gridLayoutManager =new GridLayoutManager(getActivity(),2);
                mRecycleView.setLayoutManager(gridLayoutManager);
               mRecycleView.setAdapter(new MyAdatper());
                ArrayList<String> banner= courseModel.data.banner;

                ImageView imageView1 =new ImageView(getActivity());
                x.image().bind(imageView1,banner.get(banner.size()-1));
                mViewPagerImgs.add(imageView1);

                for (int i=0;i<banner.size();i++){

                    ImageView imageView = new ImageView(getActivity());
                    x.image().bind(imageView,banner.get(i));   //准备数据控件
                    mViewPagerImgs.add(imageView);
                }

                ImageView imageView2 =new ImageView(getActivity());
                x.image().bind(imageView2,banner.get(0));
                mViewPagerImgs.add(imageView2);


                mViewpager.setAdapter(new MyViewPagerAdatper());
                Log.i("CourseActivity","onSuccess result"+result);


               mViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                   @Override
                   public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                   }

                   @Override
                   public void onPageSelected(int position) {
                            curentpostion=position;
                   }

                   @Override
                   public void onPageScrollStateChanged(int state) {
                          if ((state != ViewPager.SCROLL_STATE_IDLE)){//滚动结束以后再替换
                              return;
                          }
                          if (curentpostion==0){ //滚动到第一个被替换成倒数第二个
                              mViewpager.setCurrentItem(mViewPagerImgs.size()-2,false);
                          }else  if(curentpostion ==mViewPagerImgs.size()-1){
                              mViewpager.setCurrentItem(1,false);         //滚动最后一个被替换成第第二个
                          }
                   }
               });
                mViewpager.setCurrentItem(1);
                handler.sendEmptyMessageDelayed(1,2000);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {


            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public class  MyViewPagerAdatper extends PagerAdapter{

        @Override
        public int getCount() {
            return mViewPagerImgs.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) { //viewpager滑动的时候回调方法
           ImageView imageView = mViewPagerImgs.get(position);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {  //viewpager图片滑出屏幕回调的方法
          container.removeView(mViewPagerImgs.get(position));
        }
    }

    public class  MyAdatper extends RecyclerView.Adapter<MyViewHolder>{
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
           View view =View.inflate(getActivity(),R.layout.item_course,null);
            MyViewHolder myViewHolder =new MyViewHolder(view);
            return myViewHolder;
        }
        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
                final CourseModel.Course course =courselists.get(position);
            holder.titleTv.setText(course.title);
            holder.contentTitleTv.setText(course.titlecontent);
            x.image().bind(holder.imageView,course.icon);//图片请求
            holder.mRootview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                    intent.putExtra("imgurl",course.imgurl);
                    intent.putExtra("des",course.des);
                    intent.putExtra("video",course.videourl);
                    startActivity(intent);
                }
            });
        }
        @Override
        public int getItemCount() {

            return courselists.size();//实体类的大小写
        }
    }

    public  class  MyViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView titleTv;
        TextView contentTitleTv;
        LinearLayout mRootview;

        public MyViewHolder(View itemView) {
            //创建初ViewHolder始化view
            super(itemView);
            imageView = itemView.findViewById(R.id.img);
            titleTv=itemView.findViewById(R.id.title);
            contentTitleTv =itemView.findViewById(R.id.contenttitle);
            mRootview=itemView.findViewById(R.id.rootview);
        }
    }
}
